package com.edu.springmvc.helloworld.controller;

import com.edu.springmvc.helloworld.bean.Person;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
//@ResponseBody 把返回值放到响应体中
public class ResponseTestController {
    /**
     * SpringMVC 默认返回json
     *
     * @return
     */
    @RequestMapping("/response1")
    public Person response1() {
        Person person = new Person();
        person.setName("张三");
        person.setAge(18);
        person.setIsMale(true);
        return person;
    }

    @RequestMapping("/response2")
    public Map<String, Object> response2() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 18);
        map.put("isMale", true);
        return map;
    }

    /**
     * 文件下载
     */
    @RequestMapping("/download")
//    public ResponseEntity<byte[]> download() throws UnsupportedEncodingException {
    public ResponseEntity<InputStreamResource> download() throws IOException {
//        byte[] bytes = new byte[0];
        FileInputStream fileInputStream = new FileInputStream("E:\\下载\\search.png");
        // 问题1： 文件太大，会报 OutOfMemoryError
//            bytes = fileInputStream.readAllBytes();
        InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);


        // 问题2： 乱码解决：
        String fileName = URLEncoder.encode("哈哈.png", StandardCharsets.UTF_8);

        return ResponseEntity
                .ok() // 200
                // 内容类型：流
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                // 文件长度
                .contentLength(fileInputStream.available())
                // 问题2： 中文文件名乱码
                // Content-Disposition: 内容处理方式
//                .header("Content-Disposition", "attachment;filename=哈哈.png")
                .header("Content-Disposition", "attachment;filename=" + fileName)
                .body(inputStreamResource);
    }
}
